from users.models import Role

def intial_session(user,request):
    """
    功能: 将当前登录人的所有权限录入session中
    :param user: 当前登录人

    # 查询当前登录人的角色
    # 查询当前登录人的所有权限列表
    :param request:
    :return:
    """
    permissions = Role.objects.filter(user=user).values(
        "permissions__url",
        "permissions__title",
        "permissions__menu__title",
        "permissions__menu__icon",
        "permissions__menu__pk",
    ).distinct()

    # print(permissions)


    permission_list = []  # 权限列表

    permission_menu_dict = {}  # 菜单列表

    for item in permissions:
        # 构建权限列表
        permission_list.append(item["permissions__url"])
        # 构建菜单字典

        menu_pk = item['permissions__menu__pk']
        if menu_pk:
            if menu_pk in permission_menu_dict:
                permission_menu_dict.get(menu_pk)["children"].append({
                    "title": item["permissions__title"],
                    "url": item["permissions__url"]
                })
            else:
                permission_menu_dict[menu_pk] = {
                    "menu_title":item["permissions__menu__title"],
                    "menu_icon":item["permissions__menu__icon"],
                    "children":[
                        {
                            "title": item["permissions__title"],
                            "url": item["permissions__url"]
                        }
                    ],
                }


    # 将当前登录人的权限列表注入session中
    request.session["permission_list"] = permission_list
    #菜单信息注入session
    request.session["permission_menu_dict"] = permission_menu_dict